//
//  HMEmoticonCell.swift
//  表情键盘
//
//  Created by Apple on 16/7/28.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

/// 一页有20个表情按钮
let HMEmoticonNumberOfPage = 20

/// 一页有7列
let HMEmoticonNumberColumnOfPage = 7

/// 一页有3行
let HMEmoticonNumberRowOfPage = 3

// 代理
// 1.定义协议
protocol HMEmoticonCellDelegate: NSObjectProtocol {
    // 2.定义方法
    func emoticonCellDidClick(emoticonModel model: HMEmoticonModel)
    
    func emoticonCellDidClickDeleteButton()
}

/// 表情cell,里面20个表情按钮和一个删除按钮
class HMEmoticonCell: UICollectionViewCell {
    // 3.定义代理属性
    weak var delegate: HMEmoticonCellDelegate?
    
    /// cell对应的indexPath
    var indexPath: NSIndexPath? {
        didSet {
            debugLabel.text = "我是第 \(indexPath!.section) 组,第 \(indexPath!.item) 个cell"
            
            recentLabel.hidden = (indexPath!.section != 0)
        }
    }
    
    /// 一个cell要显示的模型(20个,一页表情)
    var pageEmoticons: [HMEmoticonModel]? {
        didSet {
            // 隐藏所有按钮
            for emoticonButton in emoticonButtons {
                emoticonButton.hidden = true
            }
            
            // 将表请模型设置到按钮上面
            // 一页最多20个表情模型,也有可能少于20个
            for (index, emoitconModel) in pageEmoticons!.enumerate() {
                // 拿到每个模型,拿到对应的按钮
                let emoticonButton = emoticonButtons[index]
                
                // 将模型赋值给按钮
                emoticonButton.emoticonModel = emoitconModel
                
                // 要显示表情的按钮就不隐藏
                emoticonButton.hidden = false
            }
        }
    }
    
    /// 保存20个表情按钮
    private var emoticonButtons: [HMEmoticonButton] = [HMEmoticonButton]()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        backgroundColor = UIColor(white: 237 / 255.0, alpha: 1)
    }
    
    private func setupUI() {
        createEmoticons()
        self.contentView.addSubview(deleteButton)
        setupRecentLabel()
        
        // 添加调试label
        self.contentView.addSubview(debugLabel)
    }
    
    private func setupRecentLabel() {
        self.contentView.addSubview(recentLabel)
        
        recentLabel.translatesAutoresizingMaskIntoConstraints = false
        
        self.contentView.addConstraint(NSLayoutConstraint(item: recentLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.contentView.addConstraint(NSLayoutConstraint(item: recentLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -5))
    }
    
    // MARK: - 按钮点击事件
    @objc private func buttonClick(button: HMEmoticonButton) {
        // 4.调用代理方法
        delegate?.emoticonCellDidClick(emoticonModel: button.emoticonModel!)
    }
    
    @objc private func deleteButtonClick() {
        delegate?.emoticonCellDidClickDeleteButton()
    }

    /// 创建20个表情按钮
    private func createEmoticons() {
        for _ in 0..<HMEmoticonNumberOfPage {
            let button = HMEmoticonButton()
//            button.backgroundColor = UIColor.randomColor()
            
            self.contentView.addSubview(button)
            emoticonButtons.append(button)
            
            // 添加点击事件
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 知道cell的大小,布局20个表情按钮的位置
        layoutEmoticonButtons()
    }
    
    /// 布局表情按钮
    private func layoutEmoticonButtons() {
        // cell左右间距
        let lrMargin: CGFloat = 5
        let bottomMargin: CGFloat = 25
        
        // 计算一个按钮的宽和高
        let itemWith = (self.frame.width - 2 * lrMargin) / CGFloat(HMEmoticonNumberColumnOfPage)
        let itemHeight = (self.frame.height - bottomMargin) / CGFloat(HMEmoticonNumberRowOfPage)
        
        // 遍历每个按钮计算frame
        for (index, button) in emoticonButtons.enumerate() {
            // 计算在哪列
            let column = index % HMEmoticonNumberColumnOfPage
            // 计算在哪行
            let row = index / HMEmoticonNumberColumnOfPage
            
            // 计算x 和y
            let x = lrMargin + CGFloat(column) * itemWith
            let y = CGFloat(row) * itemHeight
            
            // 设置按钮的frame
            button.frame = CGRect(x: x, y: y, width: itemWith, height: itemHeight)
        }
        
        // 删除按钮,固定在第6列第2行
        let x = lrMargin + CGFloat(HMEmoticonNumberColumnOfPage - 1) * itemWith
        let y = CGFloat(HMEmoticonNumberRowOfPage - 1) * itemHeight
        deleteButton.frame = CGRect(x: x, y: y, width: itemWith, height: itemHeight)
    }
    
    // MARK: - 懒加载
    private lazy var debugLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 370, height: 200))
        
        // 设置
        label.textColor = UIColor.redColor()
        label.font = UIFont.systemFontOfSize(25)
        label.hidden = true
        
        return label
    }()
    
    /// 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        
        // 设置
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    /// 最近提示label
    private lazy var recentLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.text = "最近使用的表情"
        label.textColor = UIColor.lightGrayColor()
        label.font = UIFont.systemFontOfSize(13)
        label.sizeToFit()
        
        return label
    }()
}
